package org.dxy.domain.handler.process;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.handler.CommandHandler;
import org.dxy.domain.port.repository.IProcessRepository;
import org.dxy.domain.command.process.FailProcessCommand;
import org.dxy.domain.model.aggregate.Process;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 工序失败命令处理器
 * @author: dxy
 * @createTime: 2025/6/22 17:34
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class FailProcessCommandHandler implements CommandHandler<FailProcessCommand, Void> {

    private final IProcessRepository processRepository;
    private final EventBus eventBus;

    @Override
    public CommandResult<Void> handle(FailProcessCommand command) {
        // 1. 获取工序聚合根
        Process process = processRepository.findById(command.processId());
        if (process == null) {
            return CommandResult.fail("工序不存在");
        }

        try {
            // 2. 执行业务操作
            process.fail(command);

            // 3. 保存聚合根
            processRepository.save(process);

            // 4. 发布所有事件
            process.getDomainEvents().forEach(eventBus::post);

            // 5. 清理事件
            process.clearDomainEvents();

            log.info("工序失败处理成功, command={}", command);
            return CommandResult.success(null, "工序失败处理成功");
        } catch (IllegalStateException e) {
            log.warn("工序失败处理失败，原因：{}", e.getMessage());
            return CommandResult.fail(e.getMessage());
        }
    }
} 